package cn.icast.netty.c6;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Random;

public class HelloWorldClient {
    static final Logger log= LoggerFactory.getLogger(HelloWorldClient.class);
    public static void main(String[] args) {
              send();
        System.out.println("finish");
    }

    private static void send() {
        NioEventLoopGroup worker=new NioEventLoopGroup();

        try {
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(worker);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                   //  channelActive会在连接channel建立成功后，会触发active
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {

                            ByteBuf buffer = ctx.alloc().buffer();
                            char c = '0';
                            final Random r = new Random();
                            //生成10个定长的字节数组全部写入到一个ByteBuf中，最后发送出去
                            //目的：检验服务器能否每次取到定长ByteBuf
                            for (int i = 0; i < 10; i++) {
                                final byte[] bytes = fill10Bytes(c, r.nextInt(10) + 1);
                                buffer.writeBytes(bytes);
                                c++;
                            }
                            ctx.channel().writeAndFlush(buffer);

                            ctx.channel().close();
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("client error",e);
        } finally {
            worker.shutdownGracefully();
        }
    }

    /**
     * 生成len个指定c字符，定长为10，多余部分使用"_"填充
     * @param c 填充字符
     * @param len 字符长度
     * @return 填充好的字节数组
     */
    public static byte[] fill10Bytes(char c, int len){
        final byte[] bytes = new byte[10];
        Arrays.fill(bytes, (byte) '-');
        for (int i = 0; i < len; i++) {
            bytes[i] = (byte) c;
        }
        System.out.println(new String(bytes));
        return bytes;
    }
}
